package ro.ubbcluj.cs.damate.managers.accountSettings;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Component;
import ro.ubbcluj.cs.damate.managers.BaseView;
import ro.ubbcluj.cs.damate.persistence.entities.User;
import ro.ubbcluj.cs.damate.services.UserService;

import javax.annotation.PostConstruct;
import java.io.Serializable;

/**
 * @author Lorand Fazakas
 */
@Component
@Scope("view")
public class AccountSettingsManager extends BaseView implements Serializable {

    @Autowired
    private UserService userService;

    @Autowired
    private transient PasswordEncoder passwordEncoder;

    private boolean changePassword;
    private User currentUser;

    @PostConstruct
    public void init() {
        this.changePassword = false;
        this.currentUser = null;
    }

    public void update() {
        if (changePassword) {
            currentUser.setPassword(passwordEncoder.encodePassword(currentUser.getPassword(), null));
        }
        userService.update(currentUser);
        init();
    }

    public User getCurrentUser() {
        if (currentUser == null) {
            this.currentUser = userService.findByUsername(getLoggedInUser());
        }
        return currentUser;
    }

    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }

    public boolean isChangePassword() {
        return changePassword;
    }

    public void setChangePassword(boolean changePassword) {
        this.changePassword = changePassword;
    }
}
